package com.wantup.demo01;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/6/25 17:36
 * <p>
 * 生产者 消费者
 * 产生的问题：
 */
public class TestProductAndConsumer {

    public static void main(String[] args) {
        Clerk clerk = new Clerk();

        Product product = new Product(clerk);
        Consumer consumer = new Consumer(clerk);

        /**
         * 会造成 有的线程没办法唤醒。
         */
        new Thread(product, "生产者 A ").start();
        new Thread(consumer, "消费者 B ").start();
        new Thread(product, "生产者 C ").start();
        new Thread(consumer, "消费者 D ").start();


    }

}


class Clerk {
    //这个商品是共享数据
    private int product = 0;

    //进货
    public synchronized void getProduct() {

        while (product >= 10) {
            System.out.println("产品已满");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }// else {
        System.out.println(Thread.currentThread().getName() + " : " + ++product);
        this.notifyAll();
//        }

    }

    //卖货
    public synchronized void sale() {
        while (product <= 0) {
            System.out.println("缺货");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } //else {
            System.out.println(Thread.currentThread().getName() + " : " + --product);
            this.notifyAll();
       // }


    }


}

//生产者
class Product implements Runnable {

    private Clerk clerk;

    public Product() {
    }

    public Product(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {

        for (int i = 0; i < 20; i++) {

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            clerk.getProduct();
        }

    }
}


class Consumer implements Runnable {
    private Clerk clerk;

    public Consumer() {
    }

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            clerk.sale();
        }
    }
}






